Page({
  data: {
    questions: [],
    itemType: []
  },
  onShow: function () {
    this.loadQuestions();
  },
  // 从云数据库获取问题数据，并按顺序排序
  loadQuestions: function () {
    const db = wx.cloud.database();
    const MAX_LIMIT=20;
    db.collection('question_daily').count().then(res => {
      const total = res.total;
      console.log(total);
      // 计算需要分几次查询
      const batchTimes = Math.ceil(total / MAX_LIMIT);
      let tasks = [];
    
      // 2. 循环查询每一批数据
      for (let i = 0; i < batchTimes; i++) {
        const promise = db.collection('question_daily')
          .orderBy('order', 'asc')
          .skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT)
          .get();
        tasks.push(promise);
      }
      Promise.all(tasks).then(res => {
        let data = [];
        res.forEach(item => {
          data = data.concat(item.data);
        });
        // console.log("全部数据：", data);
        // 此时 data 数组中包含了集合中所有的数据
        this.setData({
          questions: data
  
        });
        let itemType = [];
        // console.log(this.data.questions);
        for (let item of this.data.questions) {
          // console.log(item);
          let result=this.getType(item);
          // console.log(result);
          itemType.push(result);
          
        }
        this.setData({
          itemType:itemType
        })

      });
    }).catch(err => {
      console.error("查询失败：", err);
    });


    },
  // 新增问题，跳转到编辑页，mode为add
  onAddQuestion: function () {
    wx.navigateTo({
      url: '/pages/questionEdit/questionEdit?mode=add'
    });
  },
  // 编辑问题，传递问题ID到编辑页，mode为edit
  onEditQuestion: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/questionEdit/questionEdit?mode=edit&id=' + id
    });
  },
  // 删除问题
  onDeleteQuestion: function (e) {
    const id = e.currentTarget.dataset.id;
    const db = wx.cloud.database();
    db.collection('question_daily').doc(id).remove().then(res => {
      wx.showToast({
        title: '删除成功'
      });
      this.loadQuestions();
    }).catch(err => {
      console.error(err);
    });
  },
  // 上移问题：与前一项交换顺序字段
  onMoveUp: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    if (index <= 0) return;
    const questions = this.data.questions;
    const current = questions[index];
    const prev = questions[index - 1];
    const db = wx.cloud.database();
    const tempOrder = current.order;
    db.collection('question_daily').doc(current._id).update({
      data: {
        order: prev.order
      }
    }).then(() => {
      return db.collection('question_daily').doc(prev._id).update({
        data: {
          order: tempOrder
        }
      });
    }).then(() => {
      wx.showToast({
        title: '上移成功'
      });
      this.loadQuestions();
    }).catch(err => {
      console.error(err);
    });
  },
  // 下移问题：与后一项交换顺序字段
  onMoveDown: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const questions = this.data.questions;
    if (index >= questions.length - 1) return;
    const current = questions[index];
    const next = questions[index + 1];
    const db = wx.cloud.database();
    const tempOrder = current.order;
    db.collection('question_daily').doc(current._id).update({
      data: {
        order: next.order
      }
    }).then(() => {
      return db.collection('question_daily').doc(next._id).update({
        data: {
          order: tempOrder
        }
      });
    }).then(() => {
      wx.showToast({
        title: '下移成功'
      });
      this.loadQuestions();
    }).catch(err => {
      console.error(err);
    });
  },
  getType(item) {
    if (item.type == "radio") {
      return "单选";
    } else if (item.type == "input") {
      return "填空";
    } else if (item.type == "address") {
      return "地址";
    } else if (item.type == "slider") {
      return "滑动条";
    }
  }
});